package com.ybbase.framework.controller.system;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ybbase.framework.common.constant.CommonResultCode;
import com.ybbase.framework.common.enums.LogFunType;
import com.ybbase.framework.common.enums.LogType;
import com.ybbase.framework.common.util.BeanUtil;
import com.ybbase.framework.model.po.system.Permission;
import com.ybbase.framework.model.po.system.User;
import com.ybbase.framework.model.po.system.UserRole;
import com.ybbase.framework.service.system.DictService;
import com.ybbase.framework.service.system.LogService;
import com.ybbase.framework.service.system.PermissionService;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.web.bind.annotation.RestController;
import com.ybbase.framework.base.controller.BaseController;
import com.ybbase.framework.service.system.RoleService;
import com.ybbase.framework.model.po.system.Role;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.*;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParams;
import com.ybbase.framework.base.model.ResponseBean;

import javax.servlet.http.HttpServletRequest;

/**
 * 系统角色 前端控制器
 *
 * @author cg
 * @since 2019-11-25
 * 云平台2.0
 */
@RestController
@RequestMapping(value = "/role", produces = {"application/json;charset=UTF-8"})
@Api("系统角色")
public class RoleController extends BaseController {

    private static final Logger LOGGER = LogManager.getLogger(RoleController.class);

    @Autowired
    private RoleService targetService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private LogService logService;
    @Autowired
    private DictService dictService;


    /**
     * 系统角色分页查询
     *
     * @param pageIndex 页数
     * @param step      每页数量
     * @return ResponseBean
     * @author cg
     * @date 2019-11-25
     * @since cloud2.0
     */
    @GetMapping("/list")
    @ApiOperation(value = "系统角色分页查询", notes = "系统角色分页查询", response = ResponseBean.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "rows", value = "每页行数", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "role", value = "系统角色", dataType = "Role对象")
    })
    public ResponseBean findListByPage(@RequestParam(name = "current", defaultValue = "1") int pageIndex,
                                       @RequestParam(name = "size", defaultValue = "20") int step, Role role) {
        try {
            QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
            if (StringUtils.isNotEmpty(role.getName())) {
                queryWrapper.lambda().eq(Role::getName, role.getName());
            }
            Page<Role> page = new Page(pageIndex, step);
            targetService.page(page, queryWrapper);
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "系统角色分页查询" + CommonResultCode.SUCCESS.getMsg(), getPermission(page));
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("系统角色分页查询异常：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "系统角色分页查询" + CommonResultCode.FAIL.getMsg());
        }
    }


    /**
     * 系统角色获取全部数据
     *
     * @return ResponseBean
     * @author cg
     * @date 2019-11-25
     * @since cloud2.0
     */
    @GetMapping("/all")
    @ApiOperation(value = "系统角色获取全部数据", notes = "系统角色获取全部数据")
    public ResponseBean findAll() {
        try {
            List<Role> models = targetService.list();
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "系统角色获取全部数据" + CommonResultCode.SUCCESS.getMsg(), models);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("系统角色获取全部数据异常：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "系统角色获取全部数据" + CommonResultCode.FAIL.getMsg());
        }
    }


    /**
     * 系统角色根据ID查找数据
     *
     * @param id 唯一编码
     * @return ResponseBean
     * @author cg
     * @date 2019-11-25
     * @since cloud2.0
     */
    @GetMapping("/find")
    @ApiOperation(value = "系统角色根据ID查找数据", notes = "系统角色根据ID查找数据")
    @ApiImplicitParam(required = true, name = "id", value = "唯一编码", dataType = "Long")
    public ResponseBean find(@RequestParam("id") Long id) {
        try {
            Role role = targetService.getById(id);
            List<Role> list = new ArrayList<>();
            list.add(role);
            Page<Role> page = new Page(0, 10);
            page.setRecords(list);
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "系统角色根据ID查找数据" + CommonResultCode.SUCCESS.getMsg(), page);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("系统角色根据ID查找数据异常：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "系统角色根据ID查找数据" + CommonResultCode.FAIL.getMsg());
        }
    }

    /**
     * 系统角色保存数据
     *
     * @param role 系统角色
     * @return ResponseBean
     * @author cg
     * @date 2019-11-25
     * @since cloud2.0
     */
    @PostMapping("/save")
    @ApiOperation(value = "系统角色保存数据", notes = "系统角色保存数据")
    @ApiImplicitParam(required = true, name = "role", value = "系统角色", dataType = "Role对象")
    public ResponseBean save(@RequestBody Role role) {
        try {
//            Map<String, String[]> map = request.getParameterMap();
//            String[] ids = map.get("permissionId");
//            List<String> list = Arrays.asList(ids[0].split("\\|"));
//            BeanUtil beanUtil = new BeanUtil();
//            Role role = (Role) beanUtil.mapToObject(request.getParameterMap(), Role.class);
            targetService.saveRole(role);
            logService.saveLog(LogType.add.getEnumKey(), LogFunType.role.getEnumKey());
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "系统角色保存数据" + CommonResultCode.SUCCESS.getMsg(), role);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("系统角色保存数据：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "系统角色保存数据" + CommonResultCode.FAIL.getMsg());
        }
    }

    /**
     * 系统角色更新数据
     *
     * @param role 系统角色
     * @return ResponseBean
     * @author cg
     * @date 2019-11-25
     * @since cloud2.0
     */
    @PutMapping("/update")
    @ApiOperation(value = "系统角色更新数据", notes = "系统角色更新数据")
    @ApiImplicitParam(required = true, name = "role", value = "系统角色", dataType = "Role对象")
    public ResponseBean update(@RequestBody Role role) {
        try {
            targetService.saveRole(role);
            logService.saveLog(LogType.edit.getEnumKey(), LogFunType.role.getEnumKey());
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "系统角色更新数据" + CommonResultCode.SUCCESS.getMsg(), role);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("系统角色更新数据：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "系统角色更新数据" + CommonResultCode.FAIL.getMsg());
        }
    }

    /**
     * 系统角色删除数据
     *
     * @param roleId 角色ID
     * @return ResponseBean
     * @author cg
     * @date 2019-11-25
     * @since cloud2.0
     */
    @GetMapping("/del")
    @ApiOperation(value = "系统角色删除数据", notes = "系统角色删除数据")
    @ApiImplicitParam(required = true, name = "ids", value = "批量删除数据", dataType = "List<Long>")
    public ResponseBean del(@RequestParam("roleId") Integer roleId) {
        try {
            List<Permission> list = permissionService.getPermissionByRoleId(roleId);
            if (list == null || list.isEmpty()) {
                targetService.removeRole(roleId);
            } else {
                targetService.removeRolePer(roleId);
                targetService.removeRole(roleId);
            }
            logService.saveLog(LogType.del.getEnumKey(), LogFunType.role.getEnumKey());
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "系统角色删除数据" + CommonResultCode.SUCCESS.getMsg());
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("系统角色删除数据：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "系统角色删除数据" + CommonResultCode.FAIL.getMsg());
        }
    }

    private Page<Role> getPermission(Page<Role> page) {
        List<Role> Roles = page.getRecords();
        for (Role role : Roles) {
            role.setDataScopeStr(dictService.getDictByKeyType(role.getDataScope()+"",
                    "data_permission").getDictvalue());
            role.setPermissionList(permissionService.getPermissionByRoleId(role.getId()));
        }
        page.setRecords(Roles);
        return page;
    }

    /**
     * 根据角色id查询用户
     *
     * @param id 唯一编码
     * @return ResponseBean
     * @author cg
     * @date 2019-11-25
     * @since cloud2.0
     */
    @GetMapping("/findRoidByUser")
    @ApiOperation(value = "根据角色id查询用户", notes = "根据角色id查询用户")
    @ApiImplicitParam(required = true, name = "id", value = "唯一编码", dataType = "Long")
    public ResponseBean findRoidByUser(Integer role_id) {
        try {
            List<UserRole> list = targetService.findRoidByUser(role_id);
            if (list.size() > 0) {
                return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "该角色下存在用户" + CommonResultCode.SUCCESS.getMsg(),list);
            }
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "系统角色根据ID查找数据" + CommonResultCode.SUCCESS.getMsg());
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("系统角色根据ID查找数据异常：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "系统角色根据ID查找数据" + CommonResultCode.FAIL.getMsg());
        }
    }
}
